﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI;

namespace Web.Framework.Controls
{
    //Clases
    //cPlanProdMain
    //cPlanProdTable
    //cPlanProdRowPar
    //cPlanProdRowImpar
    //cPlanProdTableHeader
    //cPlanProdInvisible
    //cPlanProdInputCant
    //cPlanProdTdTotal
    //cPlanProdInputTotal

    [DefaultProperty("Text"), ToolboxData("<{0}:PlanProduccionCtrl runat=server></{0}:PlanProduccionCtrl>")]
    //[Designer(typeof(WebGridCtrlDesign))]
    //[DefaultEvent("OnRowChange")]
    public class PlanProduccionCtrl : WebControl
    {
        public List<CantidadesProducto> ProductosDataSource { get; set; }

        public int CellPadding { get; set; }

        public int CellSpacing { get; set; }

        public int TableBorder { get; set; }

        public string DeleteImageSrc { get; set; }

        public bool ShowDeleteButton { get; set; }

        public bool InputsReadOnly { get; set; }

        public TemporadaComercial BindTemporada { get; set; }

        public bool ShowCommandButton { get; set; }

        public bool RepeatWeeks { get; set; }

        public int RepeatPage { get; set; }

        public string ShowCommandImgSrc { get; set; }

        /// <summary>
        /// Render this control to the output parameter specified.
        /// </summary>
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            CellPadding = 2;

            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("<div class='cPlanProdMain' id='{0}' showdeletebutton='{1}' deleteimagesrc='{2}' showcommandbutton='{3}' showcommandimgsrc='{4}' >", this.ClientID, this.ShowDeleteButton.ToString().ToLower(), this.DeleteImageSrc, this.ShowCommandButton.ToString().ToLower(), this.ShowCommandImgSrc);

            if (BindTemporada != null)
            {

                builder.AppendFormat("<table cellpadding='{0}' cellspacing='{1}' border='{2}' class='cPlanProdTable' width='100%' >", CellPadding, CellSpacing, TableBorder);

                // Header
                int numeroDeSemanaDesdeQueEsEditable = BuildHeader(builder);
                // fin header
                
                if (ProductosDataSource != null && ProductosDataSource.Count > 0)
                {
                    int fila = 0;
                    int columnaSemana = 0;
                    int totalPorFila = 0;
                    foreach (CantidadesProducto cantProd in ProductosDataSource)
                    {

                        // Repito la cabecera con las semanas
                        if (RepeatWeeks && fila != 0)
                        {
                            if (fila % RepeatPage == 0)
                            {
                                BuildHeader(builder);
                            }
                        }

                        bool esPar = fila % 2 == 0;

                        builder.AppendFormat("<tr class='{0}' id='tr_row_{1}' >", esPar ? "cPlanProdRowPar" : "cPlanProdRowImpar", fila);

                        // Item  Id
                        builder.AppendFormat("<td class='cPlanProdInvisible' innerId='{0}' id='td_id_{2}' productoId='{3}'>{1}</td>", cantProd.Id, cantProd.Id, fila, cantProd.ProductoId);

                        if (ShowDeleteButton)
                        {
                            builder.AppendFormat("<td innerId='{0}' id='td_remove_{1}' class='cTdEliminar'><a id='a_planprod_remove_{1}' href='#'><img alt='' src='{2}' /></a></td>", cantProd.Id, fila, this.DeleteImageSrc);
                        }

                        if (ShowCommandButton)
                        {
                            string command = cantProd.JsCommand.Replace("%FILA%", fila.ToString());
                            builder.AppendFormat("<td innerId='{0}' id='td_command_{1}' class='cTdCommand'><a id='a_planprod_command_{1}' href=\"{3}\"><img alt='' src='{2}' /></a></td>", cantProd.Id, fila, cantProd.JsCommandImgUrl, command);
                        }

                        //Codigo
                        builder.AppendFormat("<td filaId='{5}' innerId='{0}{1}' title='{2} - {3} - {4}'>{0}{1}</td>", cantProd.ProductoIdExterno, cantProd.ColorId, cantProd.ProductoNombre, cantProd.Color, cantProd.Calidad, fila);

                        //// Artículo
                        //builder.AppendFormat("<td innerId='{0}'>{1}</td>", cantProd.ProductoIdExterno, cantProd.ProductoNombre);

                        //// Color
                        //builder.AppendFormat("<td innerId='{0}'>{1}</td>", cantProd.ColorId, cantProd.Color);

                        //// Calidad
                        //builder.AppendFormat("<td innerId='{0}'>{1}</td>", cantProd.CalidadId, cantProd.Calidad);

                        // Los TDs por temporada
                        columnaSemana = 0;
                        totalPorFila = 0;
                        string clase;

                        List<SemanaCantidadProducto> semanaListForData = cantProd.Semanas.ToList();
                        SortSemanas(semanaListForData);

                        foreach (SemanaCantidadProducto semana in semanaListForData)
                        {                            
                            clase = InputsReadOnly ? "cPlanProdInputCant inputreadonly" : "cPlanProdInputCant";

                            if (semana.Destacar)
                            {
                                clase += " cPlanProdInputCantDestacado";
                            }

                            string prohibirEdicionAnteriorStr = string.Empty;
                            if (semana.NumeroSemana < numeroDeSemanaDesdeQueEsEditable)
                            {
                               // prohibirEdicionAnteriorStr = "makeReadOnly='true'"; // Se deshabilita por ahora
                            }

                            builder.AppendFormat("<td innerId='{0}' class='cPlanProdDataTd'><input {6} class='{5}' {4} id='planprodcant_{2}_{3}' type='text' value='{1}' oldValue='{1}' title='Sem: {0}, Prod: {7}{8}' /></td>", semana.NumeroSemana, semana.Cantidad, fila, columnaSemana, InputsReadOnly ? "readonly='readonly'" : string.Empty, clase, prohibirEdicionAnteriorStr, cantProd.ProductoIdExterno, cantProd.ColorId);
                            columnaSemana++;
                            totalPorFila += semana.Cantidad;
                        }

                        builder.AppendFormat("<td class='cPlanProdTdTotal'><input class='cPlanProdInputTotal' readonly='readonly' id='planprodtotal_{0}' type='text' value='{1}' oldValue='{1}' /></td>", fila, totalPorFila);

                        builder.Append("</tr>");

                        fila++;
                    }
                }

                builder.Append("</table>");
            }

            builder.Append("</div>");

        //    builder.AppendFormat("<script type='text/javascript'>" +
        //                         " var gridCtrl = $('#{0}').get(0);" +
        //"gridCtrl.planProdCtrl = new PlanProdCtrl(gridCtrl);" +
        //"gridCtrl.planProdCtrl.Initialize();window.planProdCtrl=gridCtrl.planProdCtrl;</script>", this.ClientID);

            output.Write(builder.ToString());
        }

        private int BuildHeader(StringBuilder builder)
        {
            builder.Append("<tr class='cPlanProdTableHeader' >");
            builder.Append("<td class='cPlanProdInvisible'>Id</td>");

            if (ShowDeleteButton)
            {
                builder.Append("<td class='cPlanProdEliminarHeader' >Eliminar</td>");
            }

            if (ShowCommandButton)
            {
                builder.Append("<td class='cPlanProdCommandHeader'>Desv&iacute;os</td>");
            }

            builder.Append("<td>C&oacute;digo</td>");
            //builder.Append("<td>Art&iacute;culo</td>");
            //builder.Append("<td>Color</td>");
            //builder.Append("<td>Calidad</td>");

            // TODO: conseguir semanas segun temporadas     

            int numeroDeSemanaDesdeQueEsEditable = 0;
            List<Semana> semanaList = BindTemporada.GetSemanas().ToList();
            SortSemanas(semanaList);

            foreach (var semana in semanaList)
            {
                builder.AppendFormat("<td class='cPlanProdSemTd' title='{1} al {2}'>Sem-{0}</td>", semana.NumeroSemana, semana.Desde.ToString("dd/MM/yyyy"), semana.Hasta.ToString("dd/MM/yyyy"));
                if (semana.Hasta < DateTime.Now)
                {
                    numeroDeSemanaDesdeQueEsEditable = semana.NumeroSemana;
                }

            }

            // Una final con el total
            builder.Append("<td class='cPlanProdHeaderTdTotal'>Total</td>");

            builder.Append("</tr>");
            return numeroDeSemanaDesdeQueEsEditable;
        }

        private void SortSemanas(List<SemanaCantidadProducto> semanaList)
        {         
            semanaList.Sort((x, y) =>
            {
                if (x.Anio == y.Anio)
                {
                    return x.NumeroSemana - y.NumeroSemana;
                }
                else
                {
                    return x.Anio - y.Anio;
                }
            });
        }

        private void SortSemanas(List<Semana> semanaList)
        {
            semanaList.Sort((x, y) =>
            {
                if (x.Anio == y.Anio)
                {
                    return x.NumeroSemana - y.NumeroSemana;
                }
                else
                {
                    return x.Anio - y.Anio;
                }
            });
        }

    }
}
